<template>
    <div class="lists">
        <el-card shadow="never" class="!border-none">
            <el-form :model="formData" inline>
                <el-form-item label="优惠券名称">
                    <el-input class="ls-input" v-model="formData.name" placeholder="请输入服务名称" />
                </el-form-item>

                <el-form-item>
                    <div class="m-l-20">
                        <el-button type="primary" @click="resetPage">查询</el-button>
                        <el-button @click="resetParams">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card shadow="never" class="mt-4 !border-none">
            <el-tabs class="-mt-2" v-model="formData.type" @tab-change="resetPage" v-perms="['goods:statistics']">
                <el-tab-pane :label="`全部(${countData?.all || '0'})`" :name="0" />
                <el-tab-pane :label="`销售中(${countData?.expired || '0'})`" :name="2" />
                <el-tab-pane :label="`处理中(${countData?.inUse || '0'})`" :name="1" />
                <el-tab-pane :label="`过期(${countData?.useUp || '0'})`" :name="3" />
            </el-tabs>

            <div class="mt-2">
                <el-button type="primary" @click="handleAdd()" v-perms="['goods:add']">添加优惠券</el-button>
            </div>

            <div class="mt-4">
                <el-table ref="tableData" :data="pager.lists" style="width: 100%"
                    @selection-change="handleSelectionChange" v-loading="pager.loading">
                    <el-table-column type="selection" max-width="55" />
                    <el-table-column property="name" label="优惠券名称" min-width="260">
                        <template #default="scope">
                            <div class="flex items-center">
                                <div class="w-[60px] h-[60px]">
                                    <el-image style="width: 60px; height: 60px" :src="scope.row.imageAddress"
                                        :preview-src-list="[scope.row.imageAddress]" :hide-on-click-modal="true"
                                        :preview-teleported="true" :fit="'contain'" />
                                </div>
                                <el-tooltip :content="scope.row.name" placement="top">
                                    <div class="ml-2 truncate">{{ scope.row.name }}</div>
                                </el-tooltip>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column property="amount" label="优惠金额" min-width="145">
                        <template #default="scope"> ¥{{ scope.row.amount }} </template>
                    </el-table-column>
                    <el-table-column property="number" label="发放数量" min-width="120" />

                    <el-table-column property="status" label="优惠券状态" min-width="120">
                        <template #default="scope">
                            <el-tag type="success" v-if="scope.row.status == 0">未开始</el-tag>
                            <el-tag type="info" v-if="scope.row.status == 1">进行中</el-tag>
                            <el-tag type="Warning" v-if="scope.row.status == 2">已结束</el-tag>
                        </template>
                    </el-table-column>

                    <!--   <el-table-column
            property="startTime"
            label="开始时间"
            min-width="120"
          />
          <el-table-column property="endTime" label="结束时间" min-width="100">
            
          </el-table-column> -->
                    <el-table-column property="shareType" label="分享类型" min-width="90">
                        <template #default="scope">
                            <el-tag type="success" v-if="scope.row.shareType == 0">不分享</el-tag>
                            <el-tag type="info" v-if="scope.row.shareType == 1">二维码分享</el-tag>
                            <el-tag type="Warning" v-if="scope.row.shareType == 2">兑换码分享</el-tag>
                            <el-tag type="info" v-if="scope.row.shareType == 3">二维码分享一张优惠券</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column property="address" label="操作" width="180" fixed="right">
                        <template #default="scope">
                            <div class="flex items-center">
                                <el-link style="margin-right: 10px" type="primary" :underline="false"
                                    @click="handleEdit(scope.row)">编辑</el-link>

                                <el-link style="margin-right: 10px" v-perms="['goods:delete']" type="danger"
                                    :underline="false" @click="handleDelete(scope.row.id)">删除</el-link>
                                <el-link style="margin-right: 10px" type="success" :underline="false"
                                    @click="share(scope.row)">分享</el-link>
                                <el-link type="success" :underline="false" @click="tableinfo(scope.row)">详情</el-link>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists"></pagination>
            </div>
        </el-card>
    </div>
    <edit-popup v-if="showEdit" ref="editRef" @success="getLists" @close="showEdit = false"
        :serviceList="serviceList" />
    <el-dialog v-model="dialogVisible" title="Tips" :width="dialogwidth" :before-close="handleClose">
        <div style="    display: flex;
    flex-wrap: wrap;
    flex-direction: row;" v-if="dialogtype == 'img'">
            <div v-for="(itemimg, indeximg) in imageUrl" style=" margin:15px;    display: flex;
    flex-direction: column;
    align-items: center;">
                <el-image style="width: 200px; height: 200px;" :src="imageUrl[indeximg]" :zoom-rate="1.2" :max-scale="7"
                    :min-scale="0.2" :preview-src-list="imageUrl" :initial-index="4" fit="cover" />
                <span class="demonstration" style="font-size: 14px;margin-top: 5px;">{{ imageUrllabel[indeximg]
                    }}</span>
            </div>
        </div>
        <div v-else-if="dialogtype == 'code'">
            <div>
                <!--  <el-select v-model="userVal" placeholder="Select" style="width: 240px">
        <el-option
          v-for="(item, index) in userList"
          :key="index"
          :label="item.nickname"
          :value="item.id"
        />
      </el-select> -->
                <el-form v-for="(item, index) in formInline" :key="index" :inline="true" :model="formInline[index]"
                    class="demo-form-inline">
                    <el-form-item label="用户">
                        <el-select v-model="formInline[index].userId" placeholder="" clearable>
                            <el-option v-for="(item, index) in userList" :key="index" :label="item.nickname"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="优惠数量">
                        <el-input-number v-model="formInline[index].number" :min="1" />
                    </el-form-item>
                </el-form>
                <el-button type="primary" style="margin-left: 10px" plain @click="adduser">添加一行</el-button>
                <el-button type="primary" style="margin-left: 10px" plain @click="submit()">上传</el-button>
            </div>

            <div style="width: 100%">
                <el-table :data="tableDatalist" style="width: 100%">
                    <el-table-column prop="userName" align="center" label="用户" />
                    <el-table-column prop="number" align="center" label="次数" />
                </el-table>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import {
    apiServiceLists,
    apiServiceDel,
    apiServiceStatus,
    apiServiceStatis,
} from "@/api/service/lists";
import { apiCategoryCommonLists } from "@/api/service/category";
import { ref } from "vue";
import Pagination from "@/components/pagination/index.vue";
import { usePaging } from "@/hooks/usePaging";
import feedback from "@/utils/feedback";
import {
    getcoupondel,
    getcoupongetCouponImageapi,
    getcouponlistapi,
    getcouponshareListapi,
    getlistCountapi,
    getuserListapi,
    postlcouponshare,
} from "@/api/service/discountCoupon";

import EditPopup from "./edit.vue";
const serviceList = reactive([]);
const editRef = shallowRef<InstanceType<typeof EditPopup>>();
const showEdit = ref(false);
const handleAdd = async () => {
    showEdit.value = true;
    /* await nextTick(); */
    editRef.value?.open("add");
};
interface formDataObj {
    name: string; //服务名称
    type?: number | string; //服务状态:1-销售中;0-仓库中
    categoryId: string;
}

// 表单数据
const formData = ref<formDataObj>({
    name: "",
    type: 0,
    categoryId: "",
});

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: getcouponlistapi,
    params: formData.value,
});

// 选中的服务项目
const selectionData = ref<number[]>([]);

// 服务分类下拉数据
const categoryData = ref([]);
const cascaderRef = ref();

// 表格多选选择的数据
const handleSelectionChange = (val: Event | any) => {
    selectionData.value = val.map((item: Event | any) => item.id);
};

// 删除服务
const handleDelete = async (ids: number | Array<number>) => {
    ids = Array.isArray(ids) ? ids : [ids];
    await feedback.confirm(
        "如果该服务已被师傅关联，此次操作也会同时删除师傅关联的服务项目，请谨慎操作。"
    );
    await getcoupondel({ id: ids[0] });
    feedback.msgSuccess("操作成功");
    getLists();
    getOrderAmount();
};

// 获取分类通用列表
const getCategoryLists = async (): Promise<void> => {
    const res = await apiCategoryCommonLists();
    categoryData.value = res;
};

// 记录级联选择器所选中的最后一个元素的id
const handleChange = () => {
    const node = cascaderRef.value.getCheckedNodes();

    formData.value.categoryId = node[0]?.data.id;
};

const countData = ref<any>({});
const getOrderAmount = async () => {
    countData.value = await getlistCountapi({});
};
const handleEdit = async (data: any) => {
    showEdit.value = true;
    /* await nextTick(); */
    editRef.value?.open("edit");
    editRef.value?.getDetail(data);
};
getOrderAmount();
getLists();
getCategoryLists();
const dialogtype = ref("");
const dialogVisible = ref(false);
const tableDatalist: any = ref([]);
const userList: any = ref([]);
const dialogwidth = ref(1600);
const formInline: any = ref([
    {
        userId: "",
        number: 1,
    },
]);
const imageUrl: any = ref([]);
const imageUrllabel: any = ref([]);
const userVal = ref("");
const tableid = ref();
const share = async (row: any) => {
    formInline.value = [
        {
            userId: "",
            number: 1,
        },
    ];
    userVal.value = "";

    tableid.value = row.id;
    if (row.shareType == 1 || row.shareType == 3) {
        dialogwidth.value = 1600;
        const res = await getcoupongetCouponImageapi(row.id);
        console.log(res)



        imageUrl.value = [];
        imageUrllabel.value = [];
        for (let item in res) {
            console.log(item);
            imageUrl.value.push(`${import.meta.env.VITE_APP_BASE_URL || ""}` + "api/uploads/" + res[item]);
            imageUrllabel.value.push(item)
        }
        console.log(imageUrl)
        console.log(imageUrllabel)

        dialogtype.value = "img";
        dialogVisible.value = true;
    } else {
        dialogwidth.value = 800;

        getdialogtable();
        const res2 = await getuserListapi({ pageNo: 1, pageSize: 999 });
        console.log(res2);
        console.log("///////////////");
        userList.value = res2.lists;
        dialogtype.value = "code";
        dialogVisible.value = true;
    }
};

const getdialogtable = async () => {
    const res = await getcouponshareListapi(tableid.value);
    tableDatalist.value = res;
};
const handleClose = (done: () => void) => {
    done();
};

const adduser = () => {
    formInline.value.push({
        userId: "",
        number: 1,
    });
};
const submit = async () => {
    const res = await postlcouponshare(formInline.value, tableid.value);

    getdialogtable();
};

const tableinfo = (data: any) => {
    showEdit.value = true;
    /* await nextTick(); */
    editRef.value?.open("info");
    editRef.value?.getDetail(data);
};
</script>

<style lang="scss" scoped>
.lists {
    .el-radio-button__inner {
        padding: 8.5px 40px;
    }
}

.ls-input {
    width: 280px;
}

.el-tabs__nav-wrap::after {
    height: 1px !important;
}

:deep() .el-tabs__content {
    padding: 0;
}
</style>
